package com.hs.shirodemo01.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hs.shirodemo01.exception.ProjectException;
import com.hs.shirodemo01.pojo.TbUser;
import com.hs.shirodemo01.mapper.TbUserMapper;
import com.hs.shirodemo01.service.TbUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hs.shirodemo01.utils.Constant;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 郭敖
 * @since 2023-08-18
 */
@Service
public class TbUserServiceImpl extends ServiceImpl<TbUserMapper, TbUser> implements TbUserService {

    @Autowired
    TbUserMapper mapper;

    @Override
    public TbUser login(TbUser user) {
//        TbUser tbUser = mapper.selectByUsername(user.getUsername());
//        if (tbUser == null) {
//           throw new RuntimeException("用户名错误");
//        }
//        if (tbUser.getPassword().equals(user.getPassword())){
//            throw new RuntimeException("密码错误");
//        }
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //没有认证过
        //封装用户的登录数据,获得令牌
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        //登录 及 异常处理
        if (!subject.isAuthenticated()){
            try {
                //用户登录
                subject.login(token);
                // 登录成功后，把用户名保持到session
                subject.getSession().setAttribute("user",subject.getPrincipal());
            } catch (UnknownAccountException uae) {
                //如果用户名不存在
                throw new ProjectException("用户名不存在",Constant.UNAUTHORIZED.getCode());
            } catch (IncorrectCredentialsException ice) {
                //如果密码错误
                throw new ProjectException("密码错误",Constant.UNAUTHORIZED.getCode());
            }
        }
        return user;
    }

    @Override
    public Page<TbUser> findByPage(Integer pageNum, Integer pageSize) {
        return mapper.selectPage(new Page<TbUser>(pageNum,pageSize),null);
    }
}
